import { StyleSheet, Dimensions, PermissionsAndroid } from "react-native";
import AsyncStorage from "@react-native-community/async-storage";
// import ReactNativeRSAUtil from "react-native-rsa-util";
import md5 from "md5";
import config from "config";
import "jsencrypt";

// export { NavigationActions, StackActions } from "react-navigation";

// export { default as Storage } from './storage'

export const delay = t => new Promise(r => setTimeout(r, t));

export const createStyles = styles => StyleSheet.create(styles);

// export const createAction = type => payload => ({ type, payload });

export const getQuery = obj => {
  if (obj) {
    return Object.keys(obj)
      .map(key => {
        return `${key}=${obj[key] || ""}`;
      })
      .join("&");
  }
};

/**
 * 日期转换
 */
export function dateFormat(fmt, date) {
  // author: meizz
  // 对Date的扩展，将 Date 转化为指定格式的String
  // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
  // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  // 例子：
  // dateFormat("yyyy-MM-dd hh:mm:ss.S",date) ==> 2006-07-02 08:09:04.423
  // dateFormat("yyyy-M-d h:m:s.S",date)      ==> 2006-7-2 8:9:4.18
  const o = {
    "M+": date.getMonth() + 1, // 月份
    "d+": date.getDate(), // 日
    "h+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };
  let res = fmt;
  if (/(y+)/.test(res))
    res = res.replace(
      RegExp.$1,
      `${date.getFullYear()}`.substr(4 - RegExp.$1.length)
    );
  for (const k in o)
    if (new RegExp(`(${k})`).test(res))
      res = res.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
      );
  return res;
}

/**
 * 时间转为时间戳
 * @param time 时间(00:00:00)
 * @returns {string} 时间戳（单位：秒）
 */
export function timeToSecond(time) {
  let s = "";

  const hour = time.split(":")[0];
  const min = time.split(":")[1];
  const sec = time.split(":")[2];

  s = Number(hour * 3600) + Number(min * 60) + Number(sec);

  return s;
}

export const checkLogin = async () => {
  const token = (await getStore("token")) || "none";
  if (token) {
    return true;
  }
  return false;
};

export const setStore = async (key, value) => {
  try {
    await AsyncStorage.setItem(key, `${value}`);
  } catch (e) {
    // saving error
  }
};

export const getStore = async key => {
  try {
    const value = await AsyncStorage.getItem(key);
    return value;
  } catch (e) {
    // error reading value
  }
};

export const removeStore = async key => {
  try {
    await AsyncStorage.removeItem(key);
  } catch (e) {
    // error reading value
  }
};

// 处理服务器返回的地区数据
const trimAreasData = item => {
  const resData = {
    label: item.areaName,
    value: item.id,
  };
  if (Array.isArray(item.children) && item.children.length > 0) {
    resData.children = item.children.map(citem => trimAreasData(citem));
  }
  return resData;
};

/**
 * 工具方法，获取一个UUID
 * @returns UUID
 */
export const getUUID = () => {
  // return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
  return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, c => {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

/**
 * md5加密操作
 * @param password 密码
 * @param key 加密值
 * @returns 加密之后的字符串
 */
export const md5Encryption = (password, key) => {
  return md5(`${password}${key}`);
};

const deviceW = Dimensions.get("window").width;

const basePx = 375;
// 按比例做适配方法 宽375进行适配
export default function px2dp(px) {
  return (px * deviceW) / basePx;
}

export const keyRenderContent = (text, key = "澳門&&審批") => {
  // 特殊字符
  const specialCharater = new RegExp(
    "[`~!@#$%^&*()\\-+={}':;,\\[\\].<>/?￥…（）_|【】‘；：”“’。，、？\\s]"
  );
  if (key && text && typeof text === "string" && typeof key === "string") {
    const keyArr = key.split(specialCharater).filter(k => k);
    const newText = text.replace(
      new RegExp(keyArr.join("|"), "ig"),
      str => `<a href="javascript:void();">${str}</a>`
    );
    return newText;
  } else {
    return text;
  }
};

// 不使用分词去过滤高亮方法
export const keyRenderContentByHtml = text => {
  const re = /<em[^>]*>(.*?)<\/em>/g;
  const arr = [];
  while (re.exec(text) != null) {
    arr.push(`${RegExp.$1}\n`);
  }
  // 进行长度降序排序 如短的先排到了 那相似长度就无法识别
  const rtn = arr
    .map(i => ({ raw: i, len: i.length }))
    .sort((p, n) => n.len - p.len)
    .map(i => i.raw);
  const filters = ["<em>", "</em>"];
  const newText = text.replace(new RegExp(filters.join("|"), "ig"), "");
  // console.log(newText, rtn.join(","));
  const highLightText = keyRenderContent(newText, rtn.join(","));
  // console.log(highLightText);
  return highLightText;
};

// 不使用分词去过滤高亮方法
export const getContentByHtml = text => {
  const filters = ["<em>", "</em>"];
  const newText = text.replace(new RegExp(filters.join("|"), "ig"), "");
  return newText;
};

export const getRSAEncrypt = async msg => {
  // const result = await ReactNativeRSAUtil.encryptStringWithPublicKey(
  //   msg,
  //   config.publicKey
  // );
  return result;
};
export const getRSADecrypt = async msg => {
  // const result = await ReactNativeRSAUtil.decryptStringWithPrivateKey(
  //   msg,
  //   config.privateKey
  // );
  return result;
};

export function unique(arr) {
  if (!Array.isArray(arr)) {
    return;
  }
  arr.reverse();
  const array = [];
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < arr.length; i++) {
    if (array.indexOf(arr[i]) === -1) {
      array.push(arr[i]);
    }
  }
  array.reverse();
  return array;
}

export function CheckPassWord(password) {
  // 必须为字母加数字且长度不小于8位
  const str = password;
  if (str == null || str.length < 8) {
    return false;
  }
  if (str == null || str.length > 16) {
    return false;
  }
  const reg1 = new RegExp(/^[0-9A-Za-z]+$/);
  if (!reg1.test(str)) {
    return false;
  }
  const reg = new RegExp(/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/);
  if (reg.test(str)) {
    return true;
  } else {
    return false;
  }
}

export function isEmpty(str) {
  return str === null || str === "" || str === undefined;
}

// 不使用分词去过滤高亮方法
export const keyRenderContentByTag = text2 => {
  if (isEmpty(text2)) {
    return {};
  }
  const text = ` ${text2}`;
  const res = {};
  const re = /\[link submit=[^\]]*\](.*?)\[\/link\]/g;
  const re2 = /\[link submit="faqvote[^\]]*\](.*?)\[\/link\]/g;
  const arr = [];
  const arr2 = [];
  const arr3 = [];
  const arr4 = [];
  const arr5 = [];
  console.log("keyRenderContentByTag");
  const newText = text.replace(new RegExp("↵|\\n", "ig"), "");
  // console.log(newText);

  // 过滤link包裹的内容
  while (re.exec(newText) != null) {
    arr.push(`${RegExp.$1}`);
  }
  // console.log(arr.join(","));

  //  获取码值对应的描述
  while (re2.exec(newText) != null) {
    arr2.push(`${RegExp.$1}`);
  }
  // console.log(arr2.join(","));
  res.dataDes2 = arr2;

  // 获取码值
  const re3 = /\[link submit="faqvote:(.*?)"\]/g;
  while (re3.exec(newText) != null) {
    arr3.push(`${RegExp.$1}`);
  }
  res.dataDes3 = arr3;
  // console.log(arr3.join(","));

  //  获取展示的link
  const newText2 = arr.join("&").replace(new RegExp(arr2.join("|"), "ig"), "");
  const keyArr = newText2.split("&").filter(k => k);
  res.dataDes = keyArr;
  // 获取内容
  // 您好，关于首次办理普通护照指南[link target="_blank"  url="https://www.gdzwfw.gov.cn/portal/guide/1144040055165867744440106042001"]
  // 请点击[/link]可了解更多详情。↵<br/>您可能还关注下列相关问题：↵[link submit="普通护照网上办理流程"]
  const keyArr6 = newText.split("[link submit").filter(k => k);
  const keyArr2 = keyArr6[0].split("<br/>").filter(k => k);

  const re4 = /url="(.*?)"\]/g;
  while (re4.exec(keyArr2[0]) != null) {
    arr4.push(`${RegExp.$1}`);
  }

  if (Array.isArray(arr4) && arr4.length > 0) {
    res.data = null;
    // eslint-disable-next-line prefer-destructuring
    res.link = arr4[0];
  }

  const keyArr3 = keyArr2[0].split("[link").filter(k => k);
  // eslint-disable-next-line prefer-destructuring
  res.data = keyArr3[0]; // 正文内容
  const keyArr5 = keyArr2[0].split("[/link]").filter(k => k);
  if (Array.isArray(keyArr5) && keyArr5.length > 1) {
    const keyArr7 = keyArr5[1]; // 点击内容
    // eslint-disable-next-line prefer-destructuring
    res.dataDesSub = keyArr7;
    // 请点击内容获取
    const clickreg = /\[link[^\]]*\](.*?)\[\/link\]/g;
    while (clickreg.exec(keyArr2[0]) != null) {
      arr5.push(`${RegExp.$1}`);
    }
    if (Array.isArray(arr5) && arr5.length > 0) {
      // eslint-disable-next-line prefer-destructuring
      res.dataDesSubClick = arr5[0];
    }
  }

  console.log(res);

  // const filterTag = /\[link[^\]]*\]/g;
  // const filterTag2 = /\[\/link\]/g;
  // const keyArr3 = keyArr2[0].replace(new RegExp(filterTag, "ig"), "\n");
  // const keyArr4 = keyArr3.replace(new RegExp(filterTag2, "ig"), "");
  // const keyArr5 = keyArr4.split("<br/>").filter(k => k);
  // // eslint-disable-next-line prefer-destructuring
  // res.data = keyArr5[0];
  // console.log(keyArr4[0]);

  // return keyArr;
  // const filters = ["[link submit=\"faqvote", "[/link]"];
  // const newText = text.replace(new RegExp(filters.join("|"), "ig"), "");
  // console.log(newText, arr.join(","));
  // const newText2 = arr.join("&").replace(new RegExp(arr2.join("|"), "ig"), "");
  // console.log(newText2);
  // const keyArr = newText2.split("&").filter(k => k);
  // return keyArr;
  return res;
};

/**
 * 获取指定权限
 * @param permissionType 权限类型
 * 详细见官方文档 https://reactnative.cn/docs/permissionsandroid/
 */
export const getPermissions = permissionType => {
  return new Promise(resolve => {
    resolve(PermissionsAndroid.request(permissionType));
  });
};

/**
 * 获取指多个权限
 * @param permissionType 权限类型数组
 * 详细见官方文档 https://reactnative.cn/docs/permissionsandroid/
 */
export const getMultiplPermissions = permissionTypes => {
  return new Promise(resolve => {
    resolve(PermissionsAndroid.requestMultiple(permissionTypes));
  });
};

/**
 * 检查是否已获取指定权限
 * @param permissionType 权限类型
 * 详细见官方文档 https://reactnative.cn/docs/permissionsandroid/
 */
export const checekPermissions = permissionType => {
  return new Promise(resolve => {
    resolve(PermissionsAndroid.check(permissionType));
  });
};

// /oss/get
// 数据获取
export const photoUrl = key => {
  return `${config.server.target}/oss/get?key=${key}`;
};

// export const getRSAEncrypt = msg => {
//   const encrypt = new JSEncrypt();
//   encrypt.setPublicKey(config.publicKey);
//   const encrypted = encrypt.encrypt(msg);
//   return encrypted;
// };

// export const getRSAEncrypt2 = message => {
//   // 转base64
//   // eslint-disable-next-line no-buffer-constructor
//   const modulusKey2 = new Buffer(config.publicKey, "base64");
//   const modulusKey3 = modulusKey2.toString("hex");
//   // 准备好参数对象，这里提下，n  和  e 是与rsa modulus 方式必须的参数
//   const ConsultPublicKey = { n: modulusKey3, e: "10001" };

//   const rsaPublicKey = new RSAKey();
//   rsaPublicKey.setPublicString(JSON.stringify(ConsultPublicKey));

//   // 进行加密操作
//   const randomKeyRsa = rsaPublicKey.encrypt(message);
//   // 将加密后的数据 创建buffer，   encrypt方法的返回值就hex格式的
//   // eslint-disable-next-line no-buffer-constructor
//   const tempBuffer = new Buffer(randomKeyRsa, "hex");
//   // 将数据转成base64
//   const encodedMessage = tempBuffer.toString("base64");
//   console.log(`the encoded message is ${encodedMessage}`);

//   // eslint-disable-next-line no-buffer-constructor
//   const modulusKey4 = new Buffer(config.privateKey, "base64");
//   const modulusKey5 = modulusKey4.toString("hex");
//   // 准备好参数对象，这里提下，n  和  e 是与rsa modulus 方式必须的参数
//   const ConsultPublicKey2 = { n: modulusKey5, e: "10001" };

//   rsaPublicKey.setPrivateString(JSON.stringify(ConsultPublicKey2));
//   // 进行加密操作
//   const decryptMessage = rsaPublicKey.decrypt(randomKeyRsa);

//   console.log(`the encoded message is ${decryptMessage}`);

//   return encodedMessage;
// };
